package org.easydarwin.util;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;


import com.eju.cy.drawableview.draw.SerializablePath;

import org.easydarwin.conf.Config;
import org.easydarwin.easyrtc.MainActivity;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;

/**
 * Created by stamSuper on 2017/12/26.
 * 功能：
 */

public class SocketUtil {
    private static Socket clientSocket;
    private static BufferedWriter mWriter;
    private static BufferedReader mReader;
    private static boolean receviceMsg = true;
    public static SocketUtil instance;

    private Handler handler;
    private String friendAccout;

    public static SocketUtil getInstance(){
        if(null == instance){
            instance = new SocketUtil();
        }
        return instance;
    }
    private SocketUtil(){
        if(AccountUtil.isCustom("")){
            friendAccout = PreferenceManager.getInstance().getFriendAccount("");
        }
    }

    public void setFriendAccout(String accout){
        this.friendAccout = accout;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public void initSocket() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //在子线程中初始化Socket对象
                    clientSocket=new Socket(Config.host ,Config.port);
                    //根据clientSocket.getInputStream得到BufferedReader对象，从而从输入流中获取数据
                    mReader=new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),Config.charset));
                    //根据clientSocket.getOutputStream得到BufferedWriter对象，从而从输出流中获取数据
                    mWriter=new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream(),Config.charset));
                    while(receviceMsg){
                        if(mReader.ready()){
                            Message msg = handler.obtainMessage();
                            msg.what = Config.getRemotePath;
                            String res = mReader.readLine();
                            msg.obj = res;
                            handler.sendMessage(msg);
                        }
                        Thread.sleep(200);
                    }
                    mWriter.close();
                    mReader.close();
                    clientSocket.close();
                } catch (Exception e) {
                    LogUtil.i("======================initSocket 出现异常 = " );
                    LogUtil.e(e);
                    e.printStackTrace();
                }
            }
        }).start();
    }


    public void sendPath2Server1(ArrayList<SerializablePath> paths) {
        SerializablePath [] pathArr = new SerializablePath[paths.size()];
        paths.toArray(pathArr);
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PathFileUtil.getInstance().getFile() , false ));
            out.writeObject(pathArr);
//            LogUtil.i("===================序列化成功，---- url = " + file.getAbsolutePath());
        } catch (IOException e) {
            LogUtil.i("===================序列化失败 ");
            LogUtil.e(e);
            e.printStackTrace();
        }
    }

    public void sendPath2Server(ArrayList<SerializablePath> paths , int y , String size) {
        if(null == paths || paths.size() == 0){
            LogUtil.i("========================================数据为空");
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{\"paths\":[");
        for (SerializablePath path : paths){
            sb.append(path.toString()).append(",");
        }
        sb.deleteCharAt(sb.length() -1).append("]}");
        LogUtil.i("========================================发送的数据：" + sb.toString());
        send(sb.toString() , y , size);
    }

    private void send(final String sendMsg , final int y , final String size) {
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... params) {
                sendMsg(sendMsg , y , size);
                return null;
            }
        }.execute();
    }

    public void sendAcount2Server(final String account){
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... params) {
                sendAccount(account);
                return null;
            }
        }.execute();
    }

    /**
     * 向服务器发送消息
     */
    protected void sendMsg(String sendMsg , int y , String curScreenSize) {
        try {
            //根据clientSocket.getOutputStream得到BufferedWriter对象，从而从输出流中获取数据
            mWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream(),"utf-8"));
            String msgContent = sendMsg;
            //封装成json
            JSONObject json = new JSONObject();
            json.put("account", false);
            json.put("to", friendAccout);
            json.put("msg", msgContent);
            json.put("translateY", y);
            json.put("curScreenSize", curScreenSize);
            LogUtil.i("=========================sendMsg = " + json.toString());
            //通过BufferedWriter对象向服务器写数据
            mWriter.write(json.toString()+"\n");
            //一定要调用flush将缓存中的数据写到服务器
            mWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 向服务器发送消息
     */
    private void sendAccount(String account) {
        try {
            //根据clientSocket.getOutputStream得到BufferedWriter对象，从而从输出流中获取数据
            mWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream(),"utf-8"));
            //封装成json
            JSONObject json = new JSONObject();
            json.put("account", true);
            json.put("msg", account);
            //通过BufferedWriter对象向服务器写数据
            mWriter.write(json.toString()+"\n");
            //一定要调用flush将缓存中的数据写到服务器
            mWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
